#include "AnimationLayer.h"
#include <SECore/CoreApplication.h>
#include <SEAnimation/Entity/AnimationPayload.h>

namespace SEngine
{
    AnimationLayer::AnimationLayer(CoreApplication & app)
        : Layer(app)
    {
    }

    void AnimationLayer::Attach()
    {
        SignalEnabled.AddSlot([this](bool val) { this->SlotEnabled(val); return SlotState::Keep; });
        SignalAddComponent.AddSlot([this](IComponent & comp) { this->SlotAddComponent(comp); return SlotState::Keep; });
        SignalRemoveComponent.AddSlot([this](IComponent & comp) { this->SlotRemoveComponent(comp); return SlotState::Keep; });
    }

    void AnimationLayer::Update(int delta)
    {
    }
    
    void AnimationLayer::SlotAddComponent(IComponent & comp)
    {
        if (auto anim = dynamic_cast<AnimationPayload*>(&comp); anim) {
            m_animPayloads.emplace_back(anim);
        }
    }   
    
    void AnimationLayer::SlotRemoveComponent(IComponent & comp)
    {
        if (auto anim = dynamic_cast<AnimationPayload*>(&comp); anim) {
            m_animPayloads.erase(std::remove_if(
                m_animPayloads.begin(),
                m_animPayloads.end(),
                [&]( AnimationPayload* elem ) { return elem == anim; }
            ), m_animPayloads.end());
        }
    }
    
    void AnimationLayer::SlotEnabled(bool enabled)
    {
        if (enabled) {
            for (auto anim : m_animPayloads) {
                anim->Start(200);
            }
        } else {
            for (auto anim : m_animPayloads) {
                anim->Stop();
            }
        }
    }
}